﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Drawing.Imaging;

namespace FrontEnd
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            //Program.MyNES.LoadCart(@"C:\wamp\www\jahnes\_roms\nestest.nes");
            //Program.MyNES.LoadCart(@"C:\wamp\www\jahnes\_roms\balloon.nes");
            Program.MyNES.LoadCart(@"C:\wamp\www\jahnes\_roms\DEMO.NES");
            //Program.MyNES.LaunchEmulation();
        }

        private void btnGenerateRAMDump_Click(object sender, EventArgs e)
        {
            lbRAMDump.BeginUpdate();
            //foreach (string s in Program.MyNES.GetRAMDump().Split('\n')) lbRAMDump.Items.Add(s);
            lbRAMDump.Items.RemoveAt(lbRAMDump.Items.Count - 1);
            lbRAMDump.EndUpdate();
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            string s = txtJumpTo.Text.Trim();
            int value = 0;

            bool valid_value = false;
            valid_value = cbHEX.Checked ? int.TryParse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value) : int.TryParse(s, out value);

            if ((s != string.Empty) && valid_value)
            {
                if ((lbRAMDump.Items.Count > 0) && (lbRAMDump.Items.Count > value)) lbRAMDump.SetSelected(value, true);
            }
        }

        private void frmMain_Shown(object sender, EventArgs e)
        {
            //Application.Exit();

            //Program.MyNES.LaunchEmulation();

            long[] dump = Program.MyNES.GetPatternTablesDump();
            //Application.Exit();

            unsafe
            {
                Bitmap bmp = new Bitmap(256, 64, PixelFormat.Format24bppRgb);
                BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Size.Width, bmp.Size.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
                int pixel_size = System.Drawing.Bitmap.GetPixelFormatSize(bmp.PixelFormat) / 8;
                byte* ptr = (byte*)data.Scan0;
                int index = 0;
                for (int y = 0; y < bmp.Height; y++)
                {
                    for (int x = 0; x < bmp.Width; x++)
                    {
                        ptr[y * data.Stride + x * pixel_size] = (byte)((dump[index] & 0xFF0000) >> 16);
                        ptr[y * data.Stride + x * pixel_size + 1] = (byte)((dump[index] & 0x00FF00) >> 8);
                        ptr[y * data.Stride + x * pixel_size + 2] = (byte)(dump[index++] & 0x0000FF);
                    }
                }
                bmp.UnlockBits(data);
                panel1.BackgroundImage = bmp;
                panel1.Invalidate();
            }
        }
    }
}
